import {urlDecode} from "../../../utils/tools";
import {analysisLink, gotoProfilePage, gotoTagPage} from "../../../utils/navigate";
import {Detail} from "../../../data/decoder/detail";

Page({
    data: {
        page: 1,
        statusBarHeight: getApp().globalData.statusBarHeight,
        heroBgColor: '#626c78',
        id: 0,
        title: "",
        tags: [],
        slug: "",
        firstpost: {},
        users: [],
        sticky: false,
        posts: []
    },
    onLoad: function (options) {
        const that = this
        const id = options.id,
            title = options.title,
            slug = options.slug,
            sticky = options.sticky

        // 进行数据格式化
        const tags = JSON.parse(urlDecode(options.tags)),
            firstpost = JSON.parse(urlDecode(options.firstpost)),
            users = JSON.parse(urlDecode(options.users))

        that.setData({
            id: id,
            title: title,
            tags: tags,
            slug: slug,
            firstpost: firstpost,
            users: users,
            sticky: sticky
        })

        if (tags.length > 0) {
            that.setData({
                heroBgColor: tags[0]["color"],
            })
        }

        that.loadData()
    },
    onPullDownRefresh: function() {
        const that = this
        that.setData({
            page: 1
        })
        wx.showNavigationBarLoading()
        console.log('onPullDownRefresh start')
        that.loadData()
    },
    onReachBottom: function() {
        const that = this
        wx.showNavigationBarLoading()
        console.log('onReachBottom start')
        that.loadData()
    },
    loadData: function(isAppend = false) {
        const that = this
        const detail = new Detail()
        detail.execute(that.data.id, function(data, viewData){
            const posts = viewData.posts
            const firstpost = posts.splice(0, 1)
            const tags = viewData.tags

            console.log('firstpost[0]', firstpost[0])
            that.setData({
                id: viewData.id,
                title: viewData.title,
                tags: tags,
                slug: viewData.slug,
                firstpost: firstpost[0],
                users: viewData.user,
                sticky: viewData.isSticky,
                posts: posts
            })

            if (tags.length > 0) {
                that.setData({
                    heroBgColor: tags[0]["color"],
                })
            }
            wx.hideNavigationBarLoading()
            wx.stopPullDownRefresh()
        })
    },
    flarumAvatarTap: function(e) {
        gotoProfilePage(e)
    },
    flarumNameTap: function(e) {
        gotoProfilePage(e)
    },
    gotoDiscussionByTags: function(e) {
        gotoTagPage(e)
    },
    handleTagATap: function(e) {
        analysisLink(e)
    },
});